package gin

import (
	"fmt"
	"net/http"
	"os"
	"runtime"
	"strings"
)

func Cors() HandlerFunc {
	return func(c *Ctx) {
		method := c.GetMethod()

		origin := c.Header.Get("Origin")
		var headerKeys []string
		for k, _ := range c.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		//对origin进行过滤 ---
		if origin != "" {
			// c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.SetHeader("Access-Control-Allow-Origin", origin)
			c.SetHeader("Access-Control-Allow-Headers", headerStr)
			c.SetHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			// c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			c.SetHeader("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
			// c.Header("Access-Control-Max-Age", "172800")
			c.SetHeader("Access-Control-Allow-Credentials", "true")
			c.SetHeader("content-type", "application/json")
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.Text(http.StatusOK, "Options Request!")
		}

		c.Next()
	}
}


//传入 笔记/ss/ss 或者 笔记\\ss\\ss 之类的路径
func staticDeal(basePath string) HandlerFunc{
	var dash string
	if strings.Contains(runtime.GOOS,"win") {
		dash = "\\"
	} else {
		dash = "/"
	}
	if strings.Contains(basePath,"\\") {
		basePath = strings.Join(strings.Split(basePath,"\\"),dash)
	} else {
		basePath = strings.Join(strings.Split(basePath,"/"),dash)
	}
	return func (ctx *Ctx)  {
		path := strings.Join(strings.Split(ctx.GetRestfaul("*"),"/"),dash)
		path = basePath + dash + path
		// ctx.Text(http.StatusOK,path)
		// 打开文件
		// 不用设置响应头--http.ResponseWriter 后面应该是自动判断帮我们设置了
		file,err  := os.Open(path)
		if err != nil {
			ctx.Error(http.StatusServiceUnavailable,err.Error())
		} else {
			buf := make([]byte,1024)
			for {
				n,err := file.Read(buf)
				if n==0 || err != nil {
					break
				}
				ctx.Write(buf[:n])
			}
		}
	}

}